package com.easyfun.healthmagicbox.inputviews;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easyfun.healthmagicbox.R;
import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.bluetooth.BTHandlerDispatcher;
import com.easyfun.healthmagicbox.bluetooth.BTMessageHandler;
import com.easyfun.healthmagicbox.bluetooth.BluetoothChatService;
import com.easyfun.healthmagicbox.bluetooth.DeviceListActivity;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.util.VoiceTextToValueData;
import com.easyfun.healthmagicbox.widget.zhuanpanView;
import com.easyfun.healthmagicbox.bluetooth.BTBondUtility;
import com.easyfun.healthmagicbox.comm.HealthInputDataUploadTask;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.j256.ormlite.dao.Dao;

public class HardwareInputActivity extends BaseActivity implements
		DatabaseAccess {
	// Debugging
	private static final String TAG = HardwareInputActivity.class
			.getSimpleName();
	private static final boolean D = true;

	// Intent request codes
	private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BT = 2;
	public static final int BT_RESULT_ARRIVED = 10;
	public static final int BT_INPROGRESSING = 11;
	public static final int BT_RESULT_ERROR = 12;

	// Local Bluetooth adapter
	private BluetoothAdapter mBluetoothAdapter = null;
	// Member object for the chat services
	private BluetoothChatService mChatService = null;
	// private TextView tvDeviceStatus;
	// private TextView tvDeviceName;
	protected String mConnectedDeviceName;
	private TextView measureDataTextView;
	// private TextView tvMockData;

	private List<HealthInputData> mBTResult = null;
	ListView listLastActs;

	private ArrayAdapter<String> mInputAdapter;

	public Handler uiHandler;

	// The Handler that gets information back from the BluetoothChatService
	private BTMessageHandler mHandler = null;
	private Button btn_bt_save;

	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inputhwdashboard);
		// should after set Content
		addbackButton(this);
		// personal ID
		if (!checkPersonId())
			return;

		// Get local Bluetooth adapter
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		// If the adapter is null, then Bluetooth is not supported
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "Bluetooth is not available",
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}

		measureDataTextView = (TextView) findViewById(R.id.textview_hardwareData);
		btn_bt_save = (Button) findViewById(R.id.btn_bt_save);
		btn_bt_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mBTResult != null) {
					Dao<HealthInputData, Integer> inputdao;
					try {
						inputdao = getHelper(null).getInputDataDao();
						for (HealthInputData hid : mBTResult)
							inputdao.create(hid);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				HealthInputDataUploadTask task = new HealthInputDataUploadTask(
						HardwareInputActivity.this, 
						m_personid, 
						new BasicCommCallback());
				HealthThreadPool.getInstance().execute(task);
				Toast.makeText(HardwareInputActivity.this, "保存成功！",
						Toast.LENGTH_SHORT);
				mBTResult = null;
				finish();
			}
		});

		listLastActs = (ListView) findViewById(R.id.bluedatalistview);
		mInputAdapter = new ArrayAdapter<String>(this,
				R.layout.one_lastinputlistitem, R.id.lastinputtitem_info,
				new ArrayList<String>());
		updateBlueResult(null);

		mInputAdapter.setNotifyOnChange(true);
		listLastActs.setAdapter(mInputAdapter);

		Button btn_choose_device = (Button) findViewById(R.id.btn_choose_device);
		btn_choose_device.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent serverIntent = new Intent(HardwareInputActivity.this,
						DeviceListActivity.class);
				serverIntent.putExtra(ConstantData.HMBPERSONID, m_personid);
				startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);

			}
		});

		uiHandler = new Handler() {
			@SuppressWarnings("unchecked")
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case HardwareInputActivity.BT_RESULT_ARRIVED:
					listLastActs.invalidate();
					updateBlueResult((List<HealthInputData>) msg.obj);
					break;
				case HardwareInputActivity.BT_INPROGRESSING:
					measureDataTextView.setText(String.valueOf(msg.arg1));
					measureDataTextView.invalidate();
					break;
				case HardwareInputActivity.BT_RESULT_ERROR:
					Toast.makeText(HardwareInputActivity.this, "测量出错："
							+ msg.obj + "，请重试！", Toast.LENGTH_SHORT);
					break;
				default:
					Log.e(TAG, "no handler for" + msg.what);
				}
				super.handleMessage(msg);
			}
		};
	}

	private void updateBlueResult(List<HealthInputData> inputhids) {
		mInputAdapter.clear();

		if (inputhids == null)
			return;
		mBTResult = inputhids;
		SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
		// 前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型

		for (HealthInputData hid : inputhids) {
			java.util.Date dt = new Date(Long.valueOf(hid.getValueTime()));
			String time = sdf.format(dt); // 得到精确到秒的表示：08/31/2006 21:08:00

			String value = String.format(
					ConstantData.IdToNameMapping.get(hid.getValueType()),
					hid.getValueData());
			mInputAdapter.add(time + " " + value);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (D)
			Log.e(TAG, "++ ON START ++");

		// If BT is not on, request that it be enabled.
		// setupChat() will then be called during onActivityResult
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
			// Otherwise, setup the chat session
		} else {
			// first start we don't have handler yet

			// if (mChatService == null) setupChat();
		}
	}

	@Override
	public synchronized void onResume() {
		super.onResume();
		if (D)
			Log.e(TAG, "+ ON RESUME +");

		// Performing this check in onResume() covers the case in which BT was
		// not enabled during onStart(), so we were paused to enable it...
		// onResume() will be called when ACTION_REQUEST_ENABLE activity
		// returns.
		if (mChatService != null) {
			// Only if the state is STATE_NONE, do we know that we haven't
			// started already
			if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
				// Start the Bluetooth chat services
				mChatService.start();
			}
		}
	}

	/**
	 * Sends a message.
	 * 
	 * @param message
	 *            A string of text to send.
	 */
	private void sendMessage(String message) {
		// Check that we're actually connected before trying anything
		if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
			Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
					.show();
			return;
		}

		// Check that there's actually something to send
		if (message.length() > 0) {
			// Get the message bytes and tell the BluetoothChatService to write
			byte[] send = message.getBytes();
			mChatService.write(send);

		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (D)
			Log.d(TAG, "onActivityResult " + resultCode);
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE:
			// When DeviceListActivity returns with a device to connect
			if (resultCode == Activity.RESULT_OK) {
				// Get the device MAC address
				if (data == null)
					return;
				String address = data.getExtras().getString(
						DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				String devicename = data.getExtras().getString(
						DeviceListActivity.EXTRA_DEVICE_DEVICENAME);
				// Get the BLuetoothDevice object
				BluetoothDevice device = mBluetoothAdapter
						.getRemoteDevice(address);

				Boolean returnValue = false;
				String strPsw = "0000";
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					try {
						Log.d("mylog", "NOT BOND_BONDED");
						BTBondUtility.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
						BTBondUtility.createBond(device.getClass(), device);

					} catch (Exception e) {
						// TODO Auto-generated catch block

						Log.d("mylog", "setPiN failed!");
						e.printStackTrace();
					} //

				} else {
					Log.d("mylog", "HAS BOND_BONDED");
					try {
						BTBondUtility.createBond(device.getClass(), device);
						BTBondUtility.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
						BTBondUtility.createBond(device.getClass(), device);

					} catch (Exception e) {
						// TODO Auto-generated catch block
						Log.d("mylog", "setPiN failed!");
						e.printStackTrace();
					}
				}

				// Attempt to connect to the device
				mHandler = BTHandlerDispatcher.getInstance(this).decideHandler(
						devicename, address, m_personid,
						HardwareInputActivity.this);
				setupChat2();
				mChatService.connect(device);
			}
			break;
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				// we don't have handler yet.
				// setupChat();
			} else {
				// User did not enable Bluetooth or an error occured
				Log.d(TAG, "BT not enabled");
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	private void setupChat2() {
		Log.d(TAG, "setupChat()");

		// Initialize the send button with a listener that for click events
		// mSendButton = (Button) findViewById(R.id.button_send);
		// mSendButton.setOnClickListener(new OnClickListener() {
		// public void onClick(View v) {
		// // Send a message using content of the edit text widget
		// TextView view = (TextView) findViewById(R.id.edit_text_out);
		// String message = view.getText().toString();
		// sendMessage(message);
		// }
		// });

		// Initialize the BluetoothChatService to perform bluetooth connections
		mChatService = new BluetoothChatService(this, mHandler,
				"HardwareInputActivity");

	}

	protected void updateDash(String readMessage) {
		if ((readMessage == null) || (readMessage.trim().length() == 0)) {
			return;
		}
		// tvMockData.setText(readMessage);
		measureDataTextView.setText(String.valueOf(readMessage));
/*
		int angle = VoiceTextToValueData.getIntValue(readMessage);// Integer.valueOf(readMessage);

		zhuanpanView.pointTo(angle);
*/
	}

}
